﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using AB.ServiceDirectory.BO;
using AB.ServiceDirectory.Commons;
using AB.ServiceDirectory.Entities;
using ServiceReference = AB.ServiceDirectory.Entities.ServiceReference;

namespace AB.ServiceDirectory.Design.Services
{
    public partial class ServiceDetails : Page
    {
        #region EVENTS

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// Handles the Load event of the Page control.
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.LoadSubTypes();
                this.LoadServiceTypes();
                this.LoadServiceAttendances();
                this.LoadReferralProcess();
                this.LoadReferenceData();
                this.InitMode();
            }
        }

        //protected override void OnPreLoad(EventArgs e)
        //{
        //    CheckBoxServiceExtendable.Attributes["onclick"] = "set_service_extendable()";
        //}

        /// <summary>
        /// Loads the reference data for Tab2, Tab3
        /// </summary>
        private void LoadReferenceData()
        {
            // Tab 2 reference data
            CheckBoxListBenefits.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(1);
            CheckBoxListBarriers.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(2);
            CheckBoxEthnicity.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(3);
            CheckBoxDisability.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(4);
            CheckBoxListCircumstances.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(5);
            CheckBoxListParticipation.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(6);

            CheckBoxListBenefits.DataBind();
            CheckBoxListBarriers.DataBind();
            CheckBoxEthnicity.DataBind();
            CheckBoxDisability.DataBind();
            CheckBoxListCircumstances.DataBind();
            CheckBoxListParticipation.DataBind();

            // Tab 3 reference data
            CheckBoxListClientSupportProcess.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(7);
            CheckBoxListClientOutcome.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(8);
            CheckBoxTargetClient.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(9);
            CheckBoxListClientJourney.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(10);
            CheckBoxListAccreditations.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(11);
            CheckBoxListReferralSources.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(12);
            CheckBoxListSupportCentres.DataSource = ServiceBO.GetServiceReferenceDataByCategoryId(13);

            CheckBoxListClientSupportProcess.DataBind();
            CheckBoxListClientOutcome.DataBind();
            CheckBoxTargetClient.DataBind();
            CheckBoxListClientJourney.DataBind();
            CheckBoxListAccreditations.DataBind();
            CheckBoxListReferralSources.DataBind();
            CheckBoxListSupportCentres.DataBind();
        }

        /// <summary>
        /// Loads the referral process.
        /// </summary>
        private void LoadReferralProcess()
        {
            DropDownListReferralProcess.DataSource = DocumentUtilities.ReferralProcess;
            DropDownListReferralProcess.DataBind();
            DropDownListReferralProcess.Items.Insert(0, new ListItem("None", string.Empty));
        }

        /// <summary>
        /// Loads the service attendances.
        /// </summary>
        private void LoadServiceAttendances()
        {
            DropDownListServiceAttendance.DataSource = DocumentUtilities.ServiceAttendances;
            DropDownListServiceAttendance.DataBind();
            DropDownListServiceAttendance.Items.Insert(0, new ListItem("None", string.Empty));
        }

        /// <summary>
        /// Loads the service types.
        /// </summary>
        private void LoadServiceTypes()
        {
            DropDownListServiceType.DataSource = DocumentUtilities.ServiceTypes;
            DropDownListServiceType.DataBind();
        }

        /// <summary>
        /// Loads the sub types.
        /// </summary>
        private void LoadSubTypes()
        {
            DropDownListSubType.DataSource = DocumentUtilities.ServiceSubTypes;
            DropDownListSubType.DataBind();
            DropDownListSubType.Items.Insert(0, new ListItem("None", string.Empty));
        }

        /// <summary>
        /// Inits the mode.
        /// </summary>
        private void InitMode()
        {
            int copyId = 0;
            int serviceId = 0;
            HiddenFieldServiceId.Value = serviceId.ToString(CultureInfo.CurrentCulture);

            // If copyId is existed, init copy mode for adding a new service
            if (int.TryParse(Request.Params["copyId"], out copyId))
            {
                var service = ServiceBO.GetServiceById(copyId);
                if (service != null)
                {
                    service.ServiceId = 0;
                    service.ServiceName = string.Empty;
                    LoadDetails01(service);
                    LoadDetails02AndDetails03(service);
                    ButtonSave.CommandName = "new";
                }
            }
            // If serviceid is existed, init edit mode for updating a service
            else if (int.TryParse(Request.Params["serviceId"], out serviceId))
            {
                var service = ServiceBO.GetServiceById(serviceId);
                if (service != null)
                {
                    ButtonSave.CommandName = "edit";
                    LoadDetails01(service);
                    LoadDetails02AndDetails03(service);
                }
            }
            else
            {
                ButtonSave.CommandName = "new";
                LoadDetails02AndDetails03(new Service { ServiceId = 0 });
            }
        }

        /// <summary>
        /// Loads the details01.
        /// </summary>
        /// <param name="service">The service.</param>
        private void LoadDetails01(Service service)
        {
            if (service == null)
            {
                var serviceId = int.Parse(HiddenFieldServiceId.Value);
                service = ServiceBO.GetServiceById(serviceId);
                if (service == null)
                {
                    return;
                }
            }

            // Textbox fields
            TextBoxServiceName.Text = service.ServiceName;
            TextBoxShortDescription.Text = service.ShortDescription;
            TextBoxFullDescription.Text = service.FullDescription;
            TextBoxDeptCode.Text = service.DeptCode;
            TextBoxClientDescription.Text = service.ClientDescription;
            TextBoxDescriptionDelivery.Text = service.DescriptionDelivery;
            TextBoxContractCode.Text = service.ContractCode;
            TextBoxContractValue.Text = service.ContractValue;
            TextBoxStartExpected.Text = service.StartExpected != null
                                            ? service.StartExpected.Value.ToShortDateString()
                                            : string.Empty;
            TextBoxStartDate.Text = service.StartDate != null
                                        ? service.StartDate.Value.ToShortDateString()
                                        : string.Empty;
            TextBoxEndDate.Text = service.EndDate != null ? service.EndDate.Value.ToShortDateString() : string.Empty;
            TextBoxExtendableYears.Text = service.ExtendableYears != null ? service.ExtendableYears.Value.ToString(CultureInfo.CurrentCulture) : "0";
            TextBoxExtendableMonths.Text = service.ExtendableMonths != null
                                               ? service.ExtendableMonths.Value.ToString(CultureInfo.CurrentCulture)
                                               : "0";
            TextBoxLimitedMonths.Text = service.LimitedMonths != null
                                            ? service.LimitedMonths.Value.ToString(CultureInfo.CurrentCulture)
                                            : "0";
            TextBoxLimitedYears.Text = service.LimitedYears != null
                                            ? service.LimitedYears.Value.ToString(CultureInfo.CurrentCulture) : "0";
            TextBoxLeadContact.Text = service.Contact.FirstName + " " + service.Contact.Surname;
            HiddenFieldContactId.Value = service.Contact.ContactId.ToString(CultureInfo.CurrentCulture);

            // Dropdownlist
            DropDownListSubType.SelectedValue = service.SubType;
            DropDownListServiceType.SelectedValue = service.ServiceType;
            DropDownListServiceAttendance.SelectedValue = service.Attendance;
            DropDownListReferralProcess.SelectedValue = service.ReferrealProcess;

            // Checkbox
            CheckBoxActive.Checked = service.IsActive;
            CheckBoxStagedPayment.Checked = service.ContractStagedPayment != null && service.ContractStagedPayment.Value;
            CheckBoxServiceExtendable.Checked = service.ExtendableYears != null || service.ExtendableMonths != null;
            CheckBoxTimeLimited.Checked = service.LimitedYears != null || service.LimitedMonths != null;

            // Hidden field
            HiddenFieldServiceId.Value = service.ServiceId.ToString(CultureInfo.CurrentCulture);
            HiddenFieldServiceName.Value = service.ServiceName;
        }

        /// <summary>
        /// Loads the details02.
        /// </summary>
        /// <param name="service">The service.</param>
        private void LoadDetails02AndDetails03(Service service)
        {
            ListItem listItem;
            foreach (var item in ServiceBO.GetInterventionForService(service.ServiceId))
            {
                listItem = new ListItem
                {
                    Selected = item.ServiceId != null,
                    Text = item.InterventionName,
                    Value = item.InterventionId.ToString()
                };
                CheckBoxListIntervention.Items.Add(listItem);
            }

            CheckBoxListOtherServices.DataSource = ServiceBO.GetOtherActiveService(service.ServiceId);
            CheckBoxListOtherServices.DataBind();

            DropDownListProgram.DataSource = new ProgramBO().GetProgramList(null, null, -1, -1);
            DropDownListProgram.DataBind();
            DropDownListProgram.Items.Insert(0, new ListItem("None", string.Empty));

            var serviceRef = service.ServiceReference;
            if (serviceRef == null)
            {
                var serviceId = int.Parse(HiddenFieldServiceId.Value);
                serviceRef = ServiceBO.GetServiceReferenceById(serviceId);
                if (serviceRef == null)
                {
                    return;
                }
            }

            // Tab 02
            SetSelectedItemsInCheckBoxList(serviceRef.BarriersCriterion, CheckBoxListBenefits);
            SetSelectedItemsInCheckBoxList(serviceRef.EthnicityCriterion, CheckBoxEthnicity);
            SetSelectedItemsInCheckBoxList(serviceRef.DisabilityCriterion, CheckBoxDisability);
            SetSelectedItemsInCheckBoxList(serviceRef.PersonalCircumstancesCriterion, CheckBoxListCircumstances);
            SetSelectedItemsInCheckBoxList(serviceRef.ParticipationCriterion, CheckBoxListParticipation);

            // Tab 03
            SetSelectedItemsInCheckBoxList(serviceRef.ClientSupportProcess, CheckBoxListClientSupportProcess);
            SetSelectedItemsInCheckBoxList(serviceRef.ClientOutcome, CheckBoxListClientSupportProcess);
            SetSelectedItemsInCheckBoxList(serviceRef.TargetClient, CheckBoxListClientSupportProcess);
            SetSelectedItemsInCheckBoxList(serviceRef.ClientJourney, CheckBoxListClientSupportProcess);
            SetSelectedItemsInCheckBoxList(serviceRef.ReferralSources, CheckBoxListReferralSources);
            SetSelectedItemsInCheckBoxList(serviceRef.SupportCentres, CheckBoxListSupportCentres);
        }

        /// <summary>
        /// Sets the selected items in check box list.
        /// </summary>
        /// <param name="selectedIds">The selected ids.</param>
        /// <param name="checkBoxList">The check box list.</param>
        private static void SetSelectedItemsInCheckBoxList(string selectedIds, CheckBoxList checkBoxList)
        {
            string[] selectedIdsArr = (selectedIds ?? string.Empty).Split('-');
            foreach (ListItem item in checkBoxList.Items)
            {
                if (selectedIdsArr.Contains(item.Value))
                {
                    item.Selected = true;
                }
            }
        }

        /// <summary>
        /// Gets the service details by form.
        /// </summary>
        /// <returns></returns>
        private Service GetServiceDetailsByForm()
        {
            var service = new Service();
            service.ServiceName = TextBoxServiceName.Text.Trim();
            service.ShortDescription = TextBoxShortDescription.Text.Trim();
            service.FullDescription = TextBoxFullDescription.Text.Trim();
            service.SubType = DropDownListSubType.SelectedValue;
            service.DeptCode = TextBoxDeptCode.Text.Trim();
            service.ContactId = int.Parse(HiddenFieldContactId.Value);
            service.ClientDescription = TextBoxClientDescription.Text.Trim();
            service.Attendance = DropDownListServiceAttendance.SelectedValue;
            service.ServiceType = DropDownListServiceType.SelectedValue;
            service.DescriptionDelivery = TextBoxDescriptionDelivery.Text.Trim();
            service.ContractCode = TextBoxContractCode.Text.Trim();
            service.ContractValue = TextBoxContractValue.Text.Trim();
            service.ContractStagedPayment = CheckBoxStagedPayment.Checked;
            service.ReferrealProcess = DropDownListReferralProcess.SelectedValue;
            service.IsActive = CheckBoxActive.Checked;

            // Service extendable time
            if (CheckBoxServiceExtendable.Checked)
            {
                int extendableYears, extendableMonths;
                service.ExtendableYears = int.TryParse(TextBoxExtendableYears.Text, out extendableYears) ? extendableYears : (int?)null;
                service.ExtendableMonths = int.TryParse(TextBoxExtendableMonths.Text, out extendableMonths) ? extendableMonths : (int?)null;
            }

            // Service limited time
            if (CheckBoxTimeLimited.Checked)
            {
                int limitedYears, limitedMonths;
                service.LimitedYears = int.TryParse(TextBoxLimitedYears.Text, out limitedYears)
                                           ? limitedYears
                                           : (int?)null;
                service.LimitedMonths = int.TryParse(TextBoxLimitedMonths.Text, out limitedMonths)
                                           ? limitedMonths
                                           : (int?)null;
            }

            DateTime startExpected, startDate, endDate;
            service.StartExpected = DateTime.TryParse(TextBoxStartExpected.Text, out startExpected) ? startExpected : (DateTime?)null;
            service.StartDate = DateTime.TryParse(TextBoxStartDate.Text, out startDate) ? startDate : (DateTime?)null;
            service.EndDate = DateTime.TryParse(TextBoxEndDate.Text, out endDate) ? endDate : (DateTime?)null;

            return service;
        }

        /// <summary>
        /// Gets the service reference by form.
        /// </summary>
        /// <returns></returns>
        private ServiceReference GetServiceReferenceByForm()
        {
            // Tab 2 - Reference data
            var serviceReference = new ServiceReference();
            var benefits = string.Join("-", CheckBoxListBenefits.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var barriers = string.Join("-", CheckBoxListBarriers.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var ethnicity = string.Join("-", CheckBoxEthnicity.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var disability = string.Join("-", CheckBoxDisability.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var circumstances = string.Join("-", CheckBoxListCircumstances.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var participation = string.Join("-", CheckBoxListParticipation.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));

            serviceReference.BenefitsCriterion = benefits;
            serviceReference.BarriersCriterion = barriers;
            serviceReference.EthnicityCriterion = ethnicity;
            serviceReference.DisabilityCriterion = disability;
            serviceReference.PersonalCircumstancesCriterion = circumstances;
            serviceReference.ParticipationCriterion = participation;

            // Tab 3 - Reference data - Intervention - Other service - Program
            var clientSupportProcess = string.Join("-", CheckBoxListClientSupportProcess.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var clientOutcome = string.Join("-", CheckBoxListClientOutcome.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var targetClient = string.Join("-", CheckBoxTargetClient.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var clientJourney = string.Join("-", CheckBoxListClientJourney.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var accreditation = string.Join("-", CheckBoxListAccreditations.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var referralSources = string.Join("-", CheckBoxListReferralSources.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));
            var supportCentres = string.Join("-", CheckBoxListSupportCentres.Items.Cast<ListItem>().Where(c => c.Selected).Select(c => c.Value));

            serviceReference.ClientSupportProcess = clientSupportProcess;
            serviceReference.ClientOutcome = clientOutcome;
            serviceReference.TargetClient = targetClient;
            serviceReference.ClientJourney = clientJourney;
            serviceReference.Accreditations = accreditation;
            serviceReference.ReferralSources = referralSources;
            serviceReference.SupportCentres = supportCentres;

            int programId;
            serviceReference.ProgramId = int.TryParse(DropDownListProgram.SelectedValue, out programId)
                                             ? programId
                                             : (int?)null;

            return serviceReference;
        }

        /// <summary>
        /// Gets the intervention by form.
        /// </summary>
        /// <returns></returns>
        private ICollection<Intervention> GetInterventionByForm(int serviceId)
        {
            var interventions = CheckBoxListIntervention.Items.Cast<ListItem>().Where(c => c.Selected).Select(
                        c =>
                        new Intervention { InterventionId = int.Parse(c.Value), ServiceId = serviceId }).ToList
                        ();
            return interventions;
        }

        /// <summary>
        /// Handles the Command event of the ButtonSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonSave_Command(object sender, CommandEventArgs e)
        {
            var service = GetServiceDetailsByForm();
            service.ServiceReference = GetServiceReferenceByForm();

            if (ServiceBO.AddService(service))
            {
                var intervention = GetInterventionByForm(service.ServiceId);
                ServiceBO.EditInterventionList(intervention);

                DialogBox.Success("Save the service successfully !");
            }
            else
            {
                DialogBox.Error("Cannot add the service ");
            }
        }

        /// <summary>
        /// Handles the Command event of the ButtonInactive control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonInactive_Command(object sender, CommandEventArgs e)
        {
        }

        /// <summary>
        /// Handles the Command event of the ButtonLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonLookup_Command(object sender, CommandEventArgs e)
        {
            ContactLookupPopup.Popup();
        }

        #endregion EVENTS

        protected void DropDownListSubType_SelectedIndexChanged(object sender, EventArgs e)
        {
            DetailsPanel06.Visible = false;
            DetailsPanel05.Visible = false;
            LinkDetails06.Visible = false;
            LinkDetails05.Visible = false;

            switch (DropDownListSubType.SelectedValue)
            {
                case "Contract":
                    DetailsPanel06.Visible = true;
                    LinkDetails06.Visible = true;
                    break;

                case "Funding":
                    DetailsPanel05.Visible = true;
                    LinkDetails05.Visible = true;
                    break;
            }
        }
    }
}